/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cassys.action;

import cassys.delegates.UserDelegate;
import cassys.exceptions.NoLoginException;
import cassys.exceptions.UserNotFoundException;
import com.opensymphony.xwork2.ActionContext;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.SessionAware;

/**
 *
 * @author User
 */
public class AuthenticateAction extends CassysSupport implements SessionAware {

    private String username;
    private String password;

    @Override
    public String execute() throws Exception {
        System.out.println("Logging in...");

        try {
            if (username == null || password == null) {
                return "input";
            }
            if (username.trim().length() == 0 || password.trim().length() == 0) {
                System.out.println("null");
                throw new NoLoginException("User not logged in!");
            }
            UserDelegate userManager = new UserDelegate();
            boolean isValid = userManager.userValidate(username, password);
            if (!isValid) {
                throw new UserNotFoundException("User not found");
            } else {
                System.out.println(userManager.findUserByName(username));
                session.put("user", userManager.findUserByName(username));
                return "loginsuccess";
            }

        } catch (NoLoginException e) {
            if (username.trim().length() == 0) {
                addFieldError("username", "Username is required");
            }
            if (password.trim().length() == 0) {
                addFieldError("password", "Password is required");
            }
            addActionError("User not logged in!");
            return "loginfailure";
        } catch (UserNotFoundException e) {
            addActionError("User not found");
            return "loginfailure";
        }catch (Exception e){
            return "loginfailure";
        }
    }
    
    public String logout() throws Exception {
        System.out.println("Logging out....");
        session.remove("user");
        return "input";
    }    

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setSession(Map session) {
        this.session = session;
    }
}
